package lq.gateway.filter;

import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import lq.common.entity.StudyResponse;
import lq.common.utils.StudyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import javax.servlet.http.HttpServletResponse;

/**
 * @program: cloud-study
 * @description: zuul异常
 * 包含超时,转发请求的服务不可用等异常的处理
 * 通过实现Zuul的SendErrorFilter过滤器实现
 * @author: LQ
 * @create: 2020-10-09 15:40
 */
@Slf4j
@Component
public class StudyGatewayErrorFilter extends SendErrorFilter {
    @Override
    public Object run() {
        try {
            StudyResponse studyResponse = new StudyResponse();
            /*
                获取RequestContext上下文,
                根据上下文获取serviceId(服务)
                异常对象ExceptionHolder信息
             */
            RequestContext ctx = RequestContext.getCurrentContext();
            String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
            ExceptionHolder exception = findZuulException(ctx.getThrowable());
            // 异常原因
            String errorCause = exception.getErrorCause();
            Throwable throwable = exception.getThrowable();
            // 异常信息
            String message = throwable.getMessage();
            message = StringUtils.isBlank(message) ? errorCause : message;
            studyResponse = resolveExceptionMessage(message, serviceId, studyResponse);
            HttpServletResponse response = ctx.getResponse();
            StudyUtil.makeResponse(response, MediaType.APPLICATION_JSON_UTF8_VALUE, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, studyResponse);
        } catch (Exception ex) {
            log.error("Zuul sendError", ex);
            ReflectionUtils.rethrowRuntimeException(ex);
        }
        return null;
    }

    /**
     * 根据异常信息判断异常原因,返回相应的异常对象信息
     * @param message 异常信息
     * @param serviceId 异常的服务
     * @param StudyResponse 返回的异常对象
     * @return 异常对象信息
     */
    private StudyResponse resolveExceptionMessage(String message, String serviceId, StudyResponse StudyResponse) {
        if (StringUtils.containsIgnoreCase(message, "time out")) {
            return StudyResponse.message("请求" + serviceId + "服务超时");
        }
        if (StringUtils.containsIgnoreCase(message, "forwarding error")) {
            return StudyResponse.message(serviceId + "服务不可用");
        }
        return StudyResponse.message("Zuul请求" + serviceId + "服务异常");
    }
}
